// 获取应用实例
const app = getApp()
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
const io = require('../../utils/weapp.socket.io.js')

function getRandomColor() {
  const rgb = []
  for (let i = 0; i < 3; ++i) {
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length === 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}

Page({
  data: {
    videoContext: null,
    isAutoFalse: false,
    isOwner: false,
    openId: '',
    password: '',
    name: '',
    houseId: '',
    types: ['1080', '720', '480'],
    nowType: 0,
    isPopupShow: false,
    videoName: '',
    partnerDict: {},
    userAllList: ['小阳', '小婷'],
    userChoosedList: [],
    heartInterval: null,
    statusData: {
      isPlay: 0,
      time: 0,
      uptime: 0
    },
    time: 0,
    owner: '',
    lastOpe: -1,
    isFullScreen: false,
    isPlayFlag: false,
    playFlag: false,
    pauseFlag: false,
    seekFlag: false,
    isUserModalShow: false,
    isInfoModalShow: false,
    scrollHeight: 0,
    danmuInput: '',
    msgList: [],
    msgListLength: 0,
    sendBoxBottom: 0,
    showControlBar: true,
    dragToastShow: false,
    nowFormatTime: '00:00:00',
    allFormatTime: '00:00:00',
    allTime: 0,
    isChange: false
  },

  onLoad(e) {
    this.data.openId = wx.getStorageSync('openId')
    this.data.password = wx.getStorageSync('password')
    this.data.houseId = wx.getStorageSync('houseId')
    this.data.name = wx.getStorageSync('name')

    if (e.owner == "1") {
      this.setData({
        isOwner: true
      })
    }

    if (e.change == 'true') {
      this.data.isChange = true
    }
  },

  onReady() {
    this.startSocket()
    let that = this
    this.data.videoContext = wx.createVideoContext('myVideo')
    let check = setInterval(function () {
      if (that.data.videoContext != null) {
        that.getVideoSrc('1080')
        clearInterval(check)
      }
    }, 300)
    this.calHeight()
  },

  onShow() {

  },

  onUnload() {
    if (this.socket) {
      this.socket.close()
      this.socket = null
    }
  },

  calHeight() {
    let that = this
    let query = wx.createSelectorQuery().in(this)
    query.select('#onlineList').boundingClientRect()
    query.select('#sendBox').boundingClientRect()
    query.exec(res => {
      // console.log(res)
      let scrollHeight = res[1].top - res[0].bottom - 13
      that.setData({
        scrollHeight: scrollHeight
      })
    })
  },

  getVideoSrc(type) {
    Toast.loading({
      message: '正加载资源',
      forbidClick: true,
    });
    let that = this
    wx.request({
      url: app.globalData.service + '/api/getCurrentVideo',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        houseId: that.data.houseId,
        password: that.data.password,
        type
      },
      success: function (res) {
        if (res.data.err == 0) {
          let respData = res.data.res
          console.log('getVideoSrc', respData.status)
          let status = respData.status
          let opeTime = respData.opeTime
          that.setData({
            owner: respData.owner,
            src: respData.url,
            videoName: respData.videoName,
            allFormatTime: that.formatTime(respData.totalTime),
            allTime: respData.totalTime,
            isAutoFalse: respData.isAutoFalse == '1'
          })
          // console.log('wait showStatus')
          setTimeout(() => {
            that.showStatus(status, opeTime, 1)
          }, 500);
        } else {
          Dialog.alert({
            message: res.data.res,
          })
        }
      },
      complete: function () {
        Toast.clear()
        that.getPartner()
      }
    })
  },

  getPartner() {
    Toast.loading({
      message: '正获取成员',
      forbidClick: true,
    });
    let that = this
    wx.request({
      url: app.globalData.service + '/api/getPartner',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        houseId: that.data.houseId,
        password: that.data.password,
      },
      success: function (res) {
        if (res.data.err == 0) {
          let respData = res.data.res
          that.data.partnerDict = respData
          that.showPartner()
        } else {
          Dialog.alert({
            message: res.data.res,
          })
        }
      },
      complete: function () {
        Toast.clear()
      }
    })

  },

  showPartner() {
    let that = this
    let partnerDict = this.data.partnerDict
    that.setData({
      partnerDict
    })
  },

  backTo() {
    Toast.loading({
      message: '正在返回...',
      forbidClick: true,
    });
    let that = this
    wx.request({
      url: app.globalData.service + '/api/getBackChoose',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        houseId: that.data.houseId,
        password: that.data.password,
        openId: that.data.openId
      },
      success: function (res) {
        if (res.data.err == 0) {
          that.socket.emit('backTo', {
            houseId: that.data.houseId,
            password: that.data.password,
            openId: that.data.openId,
          });
          wx.redirectTo({
            url: '../../pages/pan/index?change=true',
          })
        } else {
          Dialog.alert({
            message: res.data.res,
          })
        }
      },
      complete: function () {
        Toast.clear()
      }
    })
  },

  showPopup() {
    this.setData({
      isPopupShow: true
    })
    this.closeInfoModal()
  },

  closePopup() {
    this.setData({
      isPopupShow: false
    })
  },

  onCancelPicker() {
    this.closePopup()
  },

  onConfirmPicker(e) {
    console.log(e)
    let type = e.detail.value
    let index = e.detail.index
    this.closePopup()
    this.getVideoSrc(type)
    this.setData({
      nowType: index
    })
  },

  changeControl(e) {
    console.log(e)
    let openId = e.currentTarget.dataset.id
    let partnerDict = this.data.partnerDict
    let that = this
    Toast.loading({
      message: '正在设置',
      forbidClick: true,
    });
    wx.request({
      url: app.globalData.service + '/api/changeControl',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        houseId: that.data.houseId,
        password: that.data.password,
        openId: that.data.openId,
        userOpenId: openId
      },
      success: function (res) {
        if (res.data.err == 0) {
          partnerDict[openId].control = res.data.res
          that.setData({
            partnerDict
          })
        } else {
          that.closeUserModal()
          Dialog.alert({
            message: res.data.res,
          })
        }
      },
      complete: function () {
        Toast.clear()
      }
    })
  },

  changeAutoFalse() {
    let that = this
    Toast.loading({
      message: '正在设置',
      forbidClick: true,
    });
    wx.request({
      url: app.globalData.service + '/api/changeAutoFalse',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        houseId: that.data.houseId,
        password: that.data.password,
        openId: that.data.openId,
      },
      success: function (res) {
        if (res.data.err == 0) {
          that.setData({
            isAutoFalse: res.data.res == '1'
          })
        } else {
          that.closeUserModal()
          Dialog.alert({
            message: res.data.res,
          })
        }
      },
      complete: function () {
        Toast.clear()
      }
    })
  },

  startHeart() {

  },

  sendStatus(statusData) {
    console.log('sendStatus', statusData)
    let that = this
    this.socket.emit('changeTime', {
      houseId: that.data.houseId,
      password: that.data.password,
      openId: that.data.openId,
      status: JSON.stringify(statusData)
    });
  },

  startSocket() {
    let that = this
    Toast.loading({
      message: '正在连接...',
      forbidClick: true,
    });
    let namespace = 'socket'
    const socket = (this.socket = io(
      app.globalData.service + '/' + namespace
    ))

    socket.on('connect', function () {
      socket.emit('userJoin', {
        houseId: that.data.houseId,
        password: that.data.password,
        openId: that.data.openId,
        name: that.data.name
      });
    });

    socket.on('joinBack', function (res) {
      console.log(res)
      if (res.err == 0) {
        console.log("加入房间成功")
        if (that.data.isChange) {
          socket.emit('changeVideo', {
            houseId: that.data.houseId,
            password: that.data.password,
            openId: that.data.openId,
          })
        }
      } else {
        Dialog.alert({
          message: res.res,
        })
      }
      Toast.clear()
    });

    socket.on('newUser', function (res) {
      console.log('newUser', res)
      that.showSys(res.name + ' 加入')
      if (res.openId == that.data.openId) return
      that.data.partnerDict[res.openId] = res
      that.showPartner()
    });

    socket.on('videoChanged', function (res) {
      that.showSys('房主已更改视频')
      if (that.data.owner == '1') return
      that.getVideoSrc('1080')
    });

    socket.on('videoChanging', function (res) {
      that.showSys('房主正在更改视频')
    });

    socket.on('leaveUser', function (res) {
      console.log('leaveUser', res)
      that.showSys(res.name + ' 离开')
      delete that.data.partnerDict[res.openId]
      that.showPartner()
    });

    socket.on('timeChanged', function (res) {
      console.log('timeChanged : ', res)
      that.showSys(res.name + ' 改变进度 ' + that.formatTime(parseInt(res.status.time)))
      if (res.except == that.data.openId) return
      that.showStatus(res.status, res.opeTime, 0)
    });

    socket.on('changeMsg', function (res) {
      if (res.err == 0) {
        that.data.lastOpe = res.res
      } else {
        Dialog.alert({
          message: res.res,
        })
        that.syncStatus()
      }
    });

    socket.on('updateDanmu', function (res) {
      console.log('updateDanmu : ', res)
      if (res.openId == that.data.openId) return
      that.showDanmu(res.value, res.color)
      that.showMsg(res.value, res.openId == that.data.openId, res.name)
    });
  },

  openUserModal() {
    this.setData({
      isUserModalShow: true
    })
  },

  closeUserModal() {
    this.setData({
      isUserModalShow: false
    })
  },


  openInfoModal() {
    this.setData({
      isInfoModalShow: true
    })
  },

  closeInfoModal() {
    this.setData({
      isInfoModalShow: false
    })
  },

  syncStatus() {
    let that = this
    Toast.loading({
      message: '正在同步...',
      forbidClick: true,
    });

    wx.request({
      url: app.globalData.service + '/api/getVideoStatus',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        houseId: that.data.houseId,
        password: that.data.password,
        openId: that.data.openId
      },
      success: function (res) {
        if (res.data.err == 0) {
          let respData = res.data.res
          that.showStatus(respData.status, respData.opeTime, 1)
        } else {
          Dialog.alert({
            message: res.data.res,
          })
        }
      },
      complete: function () {
        Toast.clear()
      }
    })
  },

  showStatus(statusData, opeTime, force) {
    let isPlay = statusData.isPlay
    let time = statusData.time
    let uptime = statusData.uptime

    if (opeTime == this.data.lastOpe && force == 0) return

    let t = parseInt(new Date().getTime() / 1000)

    if (uptime == 0) {
      uptime = t
      this.data.time = time
    }

    if (isPlay == 0) {
      this.autoSeek(time)
      this.autoPause()
    } else {
      time = time + (t - uptime)
      this.autoSeek(time)
      this.autoPlay()
    }

    let that = this
    that.data.lastOpe = opeTime
    that.data.statusData = statusData
  },


  // 自己写的控件
  playVideo() {
    if (!this.data.isPlayFlag) {
      this.userPlay()
    } else {
      this.userPause()
    }
  },

  startDrag() {
    console.log('startDrag')
    this.setData({
      dragToastShow: true
    })
  },

  onDrag(e) {
    this.data.dragTime = parseInt(e.detail.value * this.data.allTime * 0.01)
    let that = this
    this.setData({
      currentValue: e.detail.value,
      nowFormatTime: that.formatTime(this.data.dragTime)
    })
  },

  stopDrag() {
    console.log('stopDrag')
    this.setData({
      dragToastShow: false
    })
    this.userSeek(this.data.dragTime)
  },

  formatTime(t) {
    let sec, min, hour
    sec = t % 60
    sec = sec < 10 ? '0' + sec : sec
    t = parseInt(t / 60)
    min = t % 60
    min = min < 10 ? '0' + min : min
    hour = parseInt(t / 60)
    hour = hour < 10 ? '0' + hour : hour
    return `${hour}:${min}:${sec}`
  },

  changeVideoFull() {
    if (this.data.isFullScreen == false) this.data.videoContext.requestFullScreen()
    else this.data.videoContext.exitFullScreen()
    this.setData({
      isFullScreen: !this.data.isFullScreen
    })
  },

  userSeek(e) {
    console.log('userSeek')
    this.data.videoContext.seek(e)
    let t = parseInt(new Date().getTime() / 1000)
    let statusData = this.data.statusData
    statusData.isPlay = this.data.isPlayFlag ? 1 : 0
    statusData.time = e
    statusData.uptime = t
    this.data.statusData = statusData
    this.sendStatus(statusData)
  },

  userPlay() {
    this.setData({
      isPlayFlag: true
    })
    console.log('userPlay')
    this.data.videoContext.play()
    let t = parseInt(new Date().getTime() / 1000)
    let statusData = this.data.statusData
    statusData.isPlay = this.data.isPlayFlag ? 1 : 0
    statusData.time = this.data.time
    statusData.uptime = t
    this.data.statusData = statusData
    this.sendStatus(statusData)
  },

  userPause() {
    this.setData({
      isPlayFlag: false
    })
    console.log('userPause')
    this.data.videoContext.pause()
    let t = parseInt(new Date().getTime() / 1000)
    let statusData = this.data.statusData
    statusData.isPlay = this.data.isPlayFlag ? 1 : 0
    statusData.time = this.data.time
    statusData.uptime = t
    this.sendStatus(statusData)
  },

  autoSeek(e) {
    console.log('autoSeek')
    this.data.videoContext.seek(e)
  },

  autoPlay() {
    console.log('autoPlay')
    this.setData({
      isPlayFlag: true
    })
    this.data.videoContext.play()
  },

  autoPause() {
    console.log('autoPause')
    this.setData({
      isPlayFlag: false
    })
    this.data.videoContext.pause()
  },

  bindTimeUpdate(e) {
    let time = e.detail.currentTime
    if (this.data.dragToastShow) return
    this.data.time = time
    let that = this
    that.setData({
      currentValue: parseFloat(time / that.data.allTime * 100).toFixed(3),
      nowFormatTime: that.formatTime(parseInt(time))
    })
  },

  bindViewClick(e) {
    this.setData({
      showControlBar: !this.data.showControlBar
    })
  },

  sendDanmu() {
    let that = this
    let temp = that.data.danmuInput
    let color = getRandomColor()
    if (temp == '') return
    this.showMsg(temp, true, that.data.name)
    that.showDanmu(temp, color)

    this.socket.emit('sendDanmu', {
      houseId: that.data.houseId,
      password: that.data.password,
      value: temp,
      color: color,
      openId: that.data.openId
    });

    that.setData({
      danmuInput: ''
    })
  },

  showDanmu(value, color) {
    this.data.videoContext.sendDanmu({
      text: value,
      color: color
    })
  },

  showMsg(value, owner, name) {
    let msgList = this.data.msgList
    msgList.push({
      value,
      owner,
      name,
      sys: false,
    })
    this.setData({
      msgList,
      msgListLength: msgList.length - 1
    })
  },

  showSys(value) {
    let msgList = this.data.msgList
    let d = new Date()
    let that = this
    msgList.push({
      value,
      sys: true,
      owner: true,
      name: 'none',
      time: that.formatDate(d)
    })
    this.setData({
      msgList,
      msgListLength: msgList.length - 1
    })
  },

  formatDate(t) {
    let hour = t.getHours()
    let min = t.getMinutes()
    hour = hour < 10 ? '0' + hour : hour
    min = min < 10 ? '0' + min : min
    return hour + ":" + min
  },

  inputFocus(e) {
    console.log(e)
    let sendBoxBottom = e.detail.height
    this.setData({
      sendBoxBottom
    })
  },

  inputBlur() {
    this.setData({
      sendBoxBottom: 0
    })
  },

  bindVideoEnterPictureInPicture() {
    console.log('进入小窗模式')
  },

  bindVideoLeavePictureInPicture() {
    console.log('退出小窗模式')
  },

  videoErrorCallback(e) {
    // console.log('视频错误信息:')
    // console.log(e.detail.errMsg)
  },

  onShareAppMessage: function () {
    let that = this
    return {
      title: '来房间一起看 《' + that.data.videoName + "》 ~",
      path: '/pages/index/index?share=true&houseId=' + that.data.houseId + '&password=' + that.data.password
    }
  }
})